package com.dzy.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dzy.base.BaseController;
import com.dzy.entity.HouseImage;
import com.dzy.result.Result;
import com.dzy.service.HouseImageService;
import com.dzy.util.QiniuUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/houseImage")
public class HouseImageController extends BaseController {
    @Reference
    private HouseImageService houseImageService;

    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(@PathVariable Long houseId, @PathVariable Integer type, Model model) {
        model.addAttribute("houseId", houseId);
        model.addAttribute("type", type);

        return "houseImage/upload";

    }

    @PostMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(@PathVariable Long houseId,
                         @PathVariable Integer type,
                         @RequestParam(value = "file") MultipartFile[] files)
            throws IOException {
        if (files != null) {
            for (MultipartFile file : files) {
                //上传图片到七牛云
                String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String fileName = UUID.randomUUID().toString();
                fileName += extName;
                QiniuUtil.upload2Qiniu(file.getBytes(), fileName);
                //QiniuUtil.upload2Qiniu(file.getBytes(),file.getOriginalFilename());//可能导致同名文件覆盖
                //写图片信息到数据库
                HouseImage houseImage = new HouseImage();
                houseImage.setType(type);
                houseImage.setHouseId(houseId);
                houseImage.setImageUrl("http://sdu5w52t1.hb-bkt.clouddn.com/" + fileName);//七牛云外链地址 为了页面展示图片
                houseImage.setImageName(fileName);//为了删除七牛云上的图片 这个字段也可以写原始文件名file.getOriginalFilename()，下载方便
                houseImageService.insert(houseImage);
            }
        }

        return Result.ok();
    }

    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable Long houseId, @PathVariable Long id) {
        HouseImage houseImage=houseImageService.getById(id);
        //删除七牛云上的照片
        QiniuUtil.deleteFileFromQiniu(houseImage.getImageName());//不能使用外链地址，要使用图片名称
        //删除数据库中的图片
        houseImageService.delete(id);
        return "redirect:/house/" + houseId;
    }


}
